package main

import (
	"encoding/json"
	"log"
	"server/http"
	"strings"
)

//定义Messag结构体
//--消息接收仅仅会从服务端接收消息
//--客户端的消息应该通过http请求的方式到达服务端
type MessagePull struct {
	From string `json:"f"`
	//to分三中形式
	//--单人推送: s single
	//--群组推送: g group
	//--全部推送: a all
	To      string `json:"t"`
	Content string `json:"c"`
}

func HandleRead(message []byte, hub *Hub, client *Client) {

	var msgP = new(MessagePull)
	err := json.Unmarshal(message, &msgP)
	if err != nil {
		log.Println(err.Error())
		//非正常消息
		msgP.To = "s1"
		msgP.Content = "test"
		return
	}

	content := []byte(msgP.Content)
	//用户和服务端的消息分离
	if msgP.From == "server" { //这里这个server值可以改动一下，省的前端瞎猜
		var sendmsg = func(cli *Client, content []byte) {
			defer func() {
				// 发生宕机时，获取panic传递的上下文并打印
				err := recover()
				if err != nil {
					//出错了就清空这个cli
					println(err)
					println("客户端已找不到")
					//todo 这里应该完善一下逻辑，查看出错的原因
					delete(hub.clis, msgP.To[1:])
				}
			}()
			cli.send <- content
		}

		switch msgP.To[0:1] {
		case "s": //单人发送 s10000
			cli, ok := hub.clis[msgP.To[1:]]
			if ok && cli != nil {
				//cli.send <- content
				sendmsg(cli, content)
			} else {
				println("客户端信息未找到")
			}
		case "g": //群组发送 g10000 10001 10002
			users := strings.Fields(msgP.To[1:])
			println(string(content))
			for _, user := range users {
				cli, ok := hub.clis[user]
				if ok {
					println(user)
					sendmsg(cli, content)
					//cli.send <- content
				}
			}
		case "a": //全员发送
			for _, cli := range hub.clis {
				sendmsg(cli, content)
				//cli.send <- content
			}
		}
	} else {
		if client == nil {
			return
		}
		if len(msgP.Content) == 0 {
			//没有消息则直接抛弃
			return
		}
		//来自客户端的消息
		//todo 验证机制？还是不应该接收用户消息，防止阻塞
		switch msgP.Content[0:1] {
		case "r": //r,初始化注册reg
			//绑定用户
			http.UserBind(msgP.From, client.key)
		case "c": //c,主动下线close
		case "h": //h,心跳heart
			http.UserHeartBeat(msgP.From, client.key)
			//client.send <- []byte(client.key)
		}
	}

}
